/**
 * Created by user on 2/13/19.
 */

import React from 'react'
import { connect } from 'react-redux'
import { EventCenter, Type, VoicePlayer } from '@utils/Global'

import { QuestionAction, MainAction } from '@act'
import { Storage, Keys } from '@utils/LocalStorage'

const zanIcon = require('@images/question/list_zan_icon.png')
const zanIconActive = require('@images/question/list_zan_icon_active.png')
class AnswerComponent extends React.Component {
  clickZan = (aItem) => {
    const { screen, dispatch } = this.props
    if (aItem.like) {
      return
    }
    let msgType = screen < 10 ? Type.COMMON_TYPE.COMMON_DM_ANSWER_UP : Type.COMMON_TYPE.COMMON_QA_ANSWER_UP
    let msg = {
      type: msgType,
      data: { answer_id: aItem.id }
    }
    dispatch(QuestionAction.doSelfLikeItem({ msgType: 'answer', id: aItem.id }))
    if (screen !== 20) {
      EventCenter.emit('send_msg_to_socket', msg)
    }
    if (screen === 20) {
      EventCenter.emit('do_replay_zan_request', { type: 'answer', id: aItem.id, from: 'list' })
    }
  }
  clickVoice = (aItem) => {
    console.log('aItem', aItem)
    let aId = `${aItem.question_id}#${aItem.user.id}#${aItem.id}`
    let voiceStatus = aItem.voiceStatus, url = aItem.data.file
    const { dispatch } = this.props
    const { updateVoiceStatus, stopAllVoice } = QuestionAction
    let status = null
    if (voiceStatus.playing || voiceStatus.loading) {
      status = this.setVoiceStatus(false, false, false, true)
      dispatch(updateVoiceStatus({aId, status, type: 'voice'}))
      VoicePlayer.stop()
      return
    }
    dispatch(stopAllVoice())
    status = this.setVoiceStatus(true, false, false, true)
    dispatch(updateVoiceStatus({aId, status, type: 'voice'}))
    this.setVoiceHasPlayed({ url })
    VoicePlayer.play(url, () => {
      status = this.setVoiceStatus(false, true, false, true)
      dispatch(updateVoiceStatus({aId, status, type: 'voice'}))
    }, () => {
      status = this.setVoiceStatus(false, false, false, true)
      dispatch(updateVoiceStatus({aId, status, type: 'voice'}))
    })
  }
  setVoiceStatus = (loading = false, playing = false, error = false, hasPlayed = true) => {
    return {
      loading: loading,
      playing: playing,
      error: error,
      hasPlayed: hasPlayed
    }
  }
  setVoiceHasPlayed({ url }) {
    const playedList = Storage.read(Keys.QA_VOICE_KEY) || []
    if (playedList.indexOf(url) < 0) {
      playedList.push(url)
      Storage.save(Keys.QA_VOICE_KEY, playedList)
    }
  }
  clickImage = (aItem) => {
    const { dispatch } = this.props
    const { toggleGlobalBigImage } = MainAction
    dispatch(toggleGlobalBigImage({url: aItem.data.file}))
  }
  renderAnswerInner(aItem, aIndex) {
    if (aItem.data.type == 0) {
      return <div className="answer_text">{aItem.data.text}</div>
    }
    if (aItem.data.type == 1) {
      return (
        <div
          className="answer_voice"
          onClick={() => {
            this.clickVoice(aItem)
          }}
        >
          <div className="answer_voice_time">{aItem.voiceStatus.record_time}"</div>
          <div className="answer_voice_blank"></div>
          { !aItem.voiceStatus.playing ? <img className="answer_voice_icon" src={require('@images/question/list_voice_icon.png')} alt=""/> : null }
          { aItem.voiceStatus.playing ? <img className="answer_voice_icon" src={require('@images/question/list_voice_icon_animate.gif')} alt=""/> : null }
          { aItem.voiceStatus.loading_voice ? <img className="answer_voice_loading" src={require('@images/question/default_loading.gif')} alt=""/> : null }
          { aItem.voiceStatus.load_error ? <img className="answer_voice_loading" src={require('@images/question/default_error.png')} alt=""/> : null }
        </div>
      )
    }
    if (aItem.data.type == 2) {
      return (
        <div onClick={() => { this.clickImage(aItem) }} className="answer_image" style={{backgroundImage: `url(${aItem.data.file})`}}></div>
      )
    }
    return null
  }
  renderAnswerList() {
    const { tItem } = this.props
    return tItem.answers.map((aItem, aIndex) => {
      return (
        <div className="single_answer" key={aIndex}>
          <img className={`answer_top_icon ${aIndex > 0 ? 'hide' : ''}`} src={require('@images/question/answer_icon.png')}/>
          { this.renderAnswerInner(aItem, aIndex) }
          { [1, 2].includes(aItem.data.type) ? <div className="answer_blank"></div> : null  }
          <div
            onClick={() => {
              this.clickZan(aItem)
            }}
            className={`a_zan_con ${aItem.like ? 'active' : ''}`}
          >
            <img className="icon" src={ aItem.like ? zanIconActive : zanIcon }/>
            <div className="count">{aItem.up_num > 999 ? '999+' : aItem.up_num}</div>
          </div>
        </div>
      )
    })
  }
  render() {
    const { tItem } = this.props
    return (
      <div className="answer_item">
        <div className="answer_top">
          { this.renderAnswerList() }
        </div>
        <div className="answer_bottom">
          <img className="a_head" src={tItem.teacher.headimgurl}/>
          <div className="a_name">{tItem.teacher.nickname || tItem.teacher.name}_{tItem.teacher.company_name}</div>
        </div>
      </div>
    )
  }
}

const AnswerComponentWithDispatch = connect()(AnswerComponent)

class QuestionListItem extends React.Component {
  clickZan = () => {
    const { item, screen, dispatch } = this.props
    if (item.like) {
      return
    }
    let msgType = screen < 10 ? Type.COMMON_TYPE.COMMON_DM_QUESTION_UP : Type.COMMON_TYPE.COMMON_QA_QUESTION_UP
    let msg = {
      type: msgType,
      data: { question_id: item.id }
    }
    dispatch(QuestionAction.doSelfLikeItem({ msgType: 'question', id: item.id }))
    if (screen !== 20) {
      EventCenter.emit('send_msg_to_socket', msg)
    }
    if (screen === 20) {
      EventCenter.emit('do_replay_zan_request', { type: 'question', id: item.id, from: 'list' })
    }
  }

  renderQuestionUsers() {
    const { item } = this.props
    return item.users.slice(0, 5).map((u, i) => {
      return (
        <img key={i} className={`d_s_user ${i == 0 ? 'no_left' : ''}`} src={u.headimgurl}/>
      )
    })
  }
  renderAnswers() {
    const { item, screen } = this.props
    return item.teachers.map((tItem, tIndex) => {
      return <AnswerComponentWithDispatch key={tIndex} tItem={tItem} tIndex={tIndex} screen={screen}/>
    })
  }
  render() {
    const { item } = this.props
    return (
      <div className="question_item">
        <div className="question_content">
          <div className={`question_text ${item.up_num > 5 ? 'has_hot' : ''}`}>
            <img className="q_icon" src={require('@images/question/question_icon.png')} alt=""/>
            { item.up_num > 5 ? <img className="q_hot_icon" src={require('@images/question/question_hot_icon.png')} alt=""/> : null }
            {item.data.text}
          </div>
          <div className="question_detail">
            <img className="d_head" src={item.user.headimgurl}/>
            <div className="d_name">{item.user.nickname || item.user.name}_{item.user.company_name}</div>
            <div className={`d_users ${item.users.length > 3 ? 'double' : ''}`}>
              { this.renderQuestionUsers() }
            </div>
            <div className={`d_zan_con ${item.like ? 'active' : ''}`}>
              <img onClick={ this.clickZan } className="icon" src={ item.like ? zanIconActive : zanIcon } />
              <span>同问</span>
              <div className="count">{item.up_num > 999 ? '999+' : item.up_num}</div>
            </div>
          </div>
        </div>
        <div className="answer_content">
          { this.renderAnswers() }
        </div>
      </div>
    )
  }
}


export default connect()(QuestionListItem)
